package com.bwton.msx.ccb.utils;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.math.BigInteger;
import java.security.MessageDigest;

import com.sensetime.ssidmobile.sdk.liveness.model.Location;
import com.sensetime.ssidmobile.sdk.liveness.constants.STImageOrientation;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.provider.MediaStore;
import android.text.TextUtils;

public class FileUtil {

    public static File mkDirs(String parentDir, String dir) {
        if (!TextUtils.isEmpty(parentDir) && !TextUtils.isEmpty(dir)) {
            final File parentFile = new File(parentDir);
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            final File targetFile = new File(parentDir, dir);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            return targetFile;
        }
        return null;
    }

    public static String copyAssetsToFile(Context context, String fileName, String destFilePath) {
        String destAbsolutePath = new StringBuilder()
                .append(destFilePath)
                .append(destFilePath.endsWith("/") ? "" : "/")
                .append(fileName)
                .toString();
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = null;
        OutputStream out = null;
        try {
            File destFile = new File(destAbsolutePath);
            // 如果文件存在且MD5一样则不需要进行复制
            if (destFile.exists()) {
                String assetFileMD5 = getFileMD5(assetManager.open(fileName));
                String destFileMD5 = getFileMD5(new FileInputStream(destFile));
                if (TextUtils.equals(assetFileMD5, destFileMD5)) {
                    return destAbsolutePath;
                }
            }
            File parentFile = destFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            destFile.createNewFile();

            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];
            int read;
            inputStream = assetManager.open(fileName);
            while ((read = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } catch (Exception e) {
            e.printStackTrace();
            destAbsolutePath = null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    destAbsolutePath = null;
                }
            }
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    destAbsolutePath = null;
                }
            }
        }
        return destAbsolutePath;
    }
    public static void export(File sourceFile,String filename,Context context){
        ContentResolver contentResolver = context.getContentResolver();
        ContentValues cv = new ContentValues();

    }
    public static void copyFile(File sourceFile, File destFile) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(sourceFile);
            if (!destFile.exists()) {
                destFile.createNewFile();
            }
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * load license content from assets file
     *
     * @param licenseFileName license file name
     * @return
     */
    public static String getLicenseContent(Context context, String licenseFileName) {
        InputStream in = null;
        try {
            in = context.getAssets().open(licenseFileName);
            return inputStream2String(in);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String getFileContent(String fileNamePath) {
        InputStream in = null;
        try {
            in = new FileInputStream(fileNamePath);
            return inputStream2String(in);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private static String inputStream2String(InputStream inputStream) {
        BufferedReader bufferedReader = null;
        try {
            StringBuilder buf = new StringBuilder();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buf.append(str);
                buf.append("\n");
            }

            String res = buf.toString();
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream fileInputStream = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            fileInputStream = new FileInputStream(file);
            while ((len = fileInputStream.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        BigInteger bigInteger = new BigInteger(1, digest.digest());
        return bigInteger.toString(16);
    }

    public static String getFileMD5(InputStream inputStream) {
        MessageDigest digest = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            while ((len = inputStream.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInteger = new BigInteger(1, digest.digest());
        return bigInteger.toString(16);
    }

    public static void saveBytes(byte[] bytes, String destFilePath) {
        if (bytes != null) {
            File destFile = new File(destFilePath);
            if (!destFile.exists()) {
                File parentFile = destFile.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                try {
                    destFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(destFile);
                fos.write(bytes, 0, bytes.length);
                fos.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static Bitmap file2Bitmap(String filePath) {
        return BitmapFactory.decodeFile(filePath);
    }

    public static File saveBGRBitmap2File(byte[] bgrBytes, int width, int height,
                                          @STImageOrientation int orientation, String filePath) {
        return saveBitmap2File(
                bgr2Bitmap(bgrBytes, width, height, orientation),
                filePath);
    }

    public static Bitmap bgr2Bitmap(byte[] bgrBytes, int width, int height) {
        return bgr2Bitmap(bgrBytes, width, height, STImageOrientation.UP);
    }

    public static Bitmap bgr2Bitmap(byte[] bgrBytes, int width, int height,
                                    @STImageOrientation int orientation) {
        Bitmap source = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        int row = height - 1, col = width - 1;
        for (int i = bgrBytes.length - 1; i >= 3; i -= 3) {
            int color = bgrBytes[i - 2] & 0xFF;
            color += (bgrBytes[i - 1] << 8) & 0xFF00;
            color += ((bgrBytes[i]) << 16) & 0xFF0000;
            source.setPixel(col--, row, color);
            if (col < 0) {
                col = width - 1;
                row--;
            }
        }
        Bitmap bitmap;
        if (orientation != STImageOrientation.UP) {
            Matrix matrix = new Matrix();
            matrix.postRotate(orientation * 90);
            bitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
                    matrix, true);
        } else {
            bitmap = source;
        }
        return bitmap;
    }

    public static File saveNV21Bitmap2File(byte[] nv21, int width, int height,
                                           @STImageOrientation int orientation,
                                           String filePath) {
        return saveBitmap2File(nv21ToBitmap(nv21, width, height, orientation), filePath);
    }

    public static File saveNV21CropBitmap2File(byte[] nv21, int width, int height,
                                               @STImageOrientation int orientation,
                                               Location location,
                                               String filePath) {
        return saveBitmap2File(nv21ToBitmap(nv21, width, height, orientation, location), filePath);
    }

    public static Bitmap nv21ToBitmap(byte[] nv21, int width, int height) {
        return nv21ToBitmap(nv21, width, height, STImageOrientation.UP, null);
    }

    public static Bitmap nv21ToBitmap(byte[] nv21, int width, int height,
                                      @STImageOrientation int orientation) {
        return nv21ToBitmap(nv21, width, height, orientation, null);
    }

    public static Bitmap nv21ToBitmap(byte[] nv21, int width, int height,
                                      @STImageOrientation int orientation,
                                      Location location) {
        YuvImage yuvImage = new YuvImage(nv21, ImageFormat.NV21, width, height, null);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Rect rectangle = new Rect(0, 0, yuvImage.getWidth(), yuvImage.getHeight());
        if (location != null) {
            rectangle.set(location.left, location.top, location.right, location.bottom);
        }
        yuvImage.compressToJpeg(rectangle, 100, out);
        byte[] data = out.toByteArray();
        Bitmap source = BitmapFactory.decodeByteArray(data, 0, data.length);
        Bitmap bitmap;
        if (orientation != STImageOrientation.UP) {
            Matrix matrix = new Matrix();
            matrix.postRotate(orientation * 90);
            bitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
                    matrix, true);
        } else {
            bitmap = source;
        }
        return bitmap;
    }

    public static File saveBitmap2File(Bitmap bitmap, String filepath) {
        File file = new File(filepath);//将要保存图片的路径
        makeDir(file);
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        } catch (IOException e) {
            e.printStackTrace();
            file = null;
        } finally {
            if (bos != null) {
                try {
                    bos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //        }
        return file;
    }

    private static void makeDir(File file) {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void deleteFiles(String filesPath) {
        new File(filesPath).deleteOnExit();
    }

    public static Bitmap byteToBitmap(byte[] imgByte) {
        InputStream input = null;
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        input = new ByteArrayInputStream(imgByte);
        SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(
                input, null, options));  //软引用防止OOM
        bitmap = (Bitmap) softRef.get();
        if (imgByte != null) {
            imgByte = null;
        }

        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException e) {
            // 异常捕获
            e.printStackTrace();
        }
        return bitmap;
    }

    public static boolean deleteFile(File file) {
        boolean isSuccess = false;
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
            isSuccess = true;
        } else {
            isSuccess = false;
        }
        return isSuccess;
    }

    public static void deleteDirWihtFile(File dir) {

        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;

        for (File file : dir.listFiles()) {

            if (file.isFile())

                file.delete(); // 删除所有文件

            else if (file.isDirectory())

                deleteDirWihtFile(file); // 递规的方式删除文件夹

        }

        dir.delete();// 删除目录本身

    }
}
